/**
 * Copyright (c) 2019 xstgongyi.org
 * All rights reserved.
 */
package org.xstgongyi.eduaid.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xstgongyi.eduaid.common.ControllerHelper;
import org.xstgongyi.eduaid.dataobject.UserDO;
import org.xstgongyi.eduaid.service.UserService;

/**
 * @author oldcrane<br/>
 * @created 2019-05-15
 */
@Controller
@RequestMapping("/users")
public class UserController {

	@Autowired
	private UserService userService;

	@GetMapping("/entry")
	public String entryPage(ModelMap map) {
		return "masterdata/user_list";
	}

	@GetMapping("")
	@ResponseBody
	public Map<String, Object> list(@RequestParam(name = "active", required = false) Boolean active,
			@RequestParam(name = "keyword", required = false) String keyword) {
		List<UserDO> users = userService.listAll(keyword, active);
		return ControllerHelper.successResponse(users);
	}

	@PostMapping("")
	@ResponseBody
	public Map<String, Object> addUser(@RequestBody UserDO user) {
		userService.insert(user.getLoginName(), user.getShowName(), user.getPassword());
		return ControllerHelper.successResponse(null);
	}

	@GetMapping("/{id}")
	@ResponseBody
	public Map<String, Object> get(@PathVariable("id") Integer id) {
		UserDO user = userService.getById(id);
		if (null != user) {
			return ControllerHelper.successResponse(user);
		} else {
			return ControllerHelper.errorResponse(404, "User does not exist(id:" + id + ").");
		}
	}

	@PostMapping("/{id}")
	@ResponseBody
	public Map<String, Object> editUser(@PathVariable("id") Integer id, @RequestBody UserDO user) {
		if (null == user) {
			return (ControllerHelper.errorResponse(1, "非法输入：要修改的用户参数为空对象。"));
		}
		user.setId(id);
		userService.update(user);
		return ControllerHelper.successResponse(null);
	}

	@PostMapping("/{id}/passwd")
	@ResponseBody
	public Map<String, Object> setPassword(@PathVariable("id") Integer id, @RequestBody UserDO user) {
		userService.setPassword(id, user.getPassword());
		return ControllerHelper.successResponse(null);
	}

}
